<template>
  <div class="adoption-detail-container">
    <el-card shadow="hover">
      <!-- 返回按钮 -->
      <div class="back-button">
        <el-button icon="el-icon-arrow-left" @click="goBack">返回列表</el-button>
      </div>

      <el-row :gutter="40" v-if="post">
        <!-- 左侧：图片展示 -->
        <el-col :xs="24" :sm="24" :md="12" :lg="12">
          <div class="image-section">
            <!-- 主图展示区域（支持鼠标悬停放大） -->
            <div class="main-image-container" @mousemove="handleMouseMove" @mouseleave="handleMouseLeave">
              <img 
                :src="mainImage" 
                :alt="post.title"
                class="main-image">
              
              <!-- 放大镜效果 -->
              <div 
                v-if="showMagnifier" 
                class="magnifier"
                :style="magnifierStyle">
              </div>
              
              <!-- 放大图片显示区域 -->
              <div 
                v-if="showMagnifier" 
                class="magnified-view"
                :style="magnifiedStyle">
              </div>
            </div>

            <!-- 缩略图列表 -->
            <div class="thumbnail-list" v-if="imageList.length > 1">
              <div 
                v-for="(image, index) in imageList" 
                :key="index"
                class="thumbnail-item"
                :class="{ active: mainImage === image }"
                @click="selectImage(image)">
                <img :src="image" :alt="`图片${index + 1}`">
              </div>
            </div>
          </div>
        </el-col>

        <!-- 右侧：帖子信息 -->
        <el-col :xs="24" :sm="24" :md="12" :lg="12">
          <div class="info-section">
            <h1 class="post-title">{{ post.title }}</h1>
            
            <div class="post-meta">
              <el-tag type="success" size="medium">{{ post.petType }}</el-tag>
              <el-tag type="warning" size="medium">{{ post.petGender }}</el-tag>
              <el-tag type="info" size="medium">{{ post.breed }}</el-tag>
              <el-tag :type="post.status === '寻找中' ? 'success' : 'info'" size="medium">{{ post.status }}</el-tag>
            </div>

            <div class="info-item">
              <div class="info-label">宠物名称</div>
              <div class="info-content">{{ post.petName }}</div>
            </div>

            <div class="info-item">
              <div class="info-label">品种</div>
              <div class="info-content">{{ post.breed }}</div>
            </div>

            <div class="info-item" v-if="post.vaccineStatus">
              <div class="info-label">疫苗情况</div>
              <div class="info-content">{{ post.vaccineStatus }}</div>
            </div>

            <div class="info-item" v-if="post.adoptionRequirement">
              <div class="info-label">领养要求</div>
              <div class="info-content">{{ post.adoptionRequirement }}</div>
            </div>

            <div class="info-item" v-if="post.location">
              <div class="info-label">地理位置</div>
              <div class="info-content">
                <i class="el-icon-location"></i>
                {{ post.location }}
              </div>
            </div>

            <div class="info-item" v-if="post.ownerInfo">
              <div class="info-label">主人信息</div>
              <div class="info-content">{{ post.ownerInfo }}</div>
            </div>

            <div class="info-item" v-if="post.description">
              <div class="info-label">详细描述</div>
              <div class="info-content description">{{ post.description }}</div>
            </div>

            <!-- 发布者信息 -->
            <div class="publisher-section">
              <div class="publisher-header">发布者信息</div>
              <div class="publisher-info">
                <img :src="post.userAvatar || 'https://img1.baidu.com/it/u=1537776144,3012351076&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500'" :alt="post.userNickname" class="publisher-avatar">
                <div class="publisher-details">
                  <div class="publisher-nickname">{{ post.userNickname || '匿名用户' }}</div>
                  <div class="publisher-phone" v-if="post.userPhone">
                    <i class="el-icon-phone"></i>
                    {{ post.userPhone }}
                  </div>
                </div>
              </div>
            </div>

            <!-- 我的帖子操作按钮 -->
            <div class="action-buttons" v-if="isMyPost">
              <el-button 
                type="warning" 
                size="large" 
                icon="el-icon-edit"
                @click="editPost">
                编辑帖子
              </el-button>
              <el-button 
                v-if="post.status === '寻找中'"
                type="info" 
                size="large" 
                icon="el-icon-check"
                @click="endPost">
                标记为已结束
              </el-button>
              <el-button 
                v-else
                type="success" 
                size="large" 
                icon="el-icon-refresh-left"
                @click="reopenPost">
                重新开始寻找
              </el-button>
            </div>
          </div>
        </el-col>
      </el-row>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <i class="el-icon-loading"></i>
        <span>加载中...</span>
      </div>
    </el-card>

    <!-- 编辑领养帖子弹窗 -->
    <el-dialog
      title="编辑领养帖子"
      :visible.sync="dialogVisible"
      width="700px"
      :close-on-click-modal="false">
      <el-form :model="postForm" label-width="100px" ref="postForm">
        <el-form-item label="标题" required>
          <el-input v-model="postForm.title" placeholder="请输入标题" maxlength="200"></el-input>
        </el-form-item>
        
        <el-form-item label="宠物类型" required>
          <el-radio-group v-model="postForm.petType">
            <el-radio label="狗">狗</el-radio>
            <el-radio label="猫">猫</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="宠物性别" required>
          <el-radio-group v-model="postForm.petGender">
            <el-radio label="公">公</el-radio>
            <el-radio label="母">母</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="宠物名称" required>
          <el-input v-model="postForm.petName" placeholder="请输入宠物名称" maxlength="50"></el-input>
        </el-form-item>
        
        <el-form-item label="品种" required>
          <el-input v-model="postForm.breed" placeholder="请输入品种" maxlength="100"></el-input>
        </el-form-item>
        
        <el-form-item label="疫苗情况">
          <el-input 
            type="textarea" 
            v-model="postForm.vaccineStatus" 
            placeholder="请输入疫苗接种情况" 
            :rows="3"
            maxlength="500"></el-input>
        </el-form-item>
        
        <el-form-item label="照片上传">
          <el-upload
            :action="uploadUrl"
            list-type="picture-card"
            :file-list="fileList"
            :on-success="handleUploadSuccess"
            :on-remove="handleRemove"
            :limit="5"
            :on-exceed="handleExceed">
            <i class="el-icon-plus"></i>
            <div slot="tip" class="el-upload__tip">最多上传5张图片，每张不超过5MB</div>
          </el-upload>
        </el-form-item>
        
        <el-form-item label="领养要求">
          <el-input 
            type="textarea" 
            v-model="postForm.adoptionRequirement" 
            placeholder="请输入领养要求" 
            :rows="4"
            maxlength="1000"></el-input>
        </el-form-item>
        
        <el-form-item label="地理位置">
          <el-input v-model="postForm.location" placeholder="请输入地理位置" maxlength="200"></el-input>
        </el-form-item>
        
        <el-form-item label="主人信息">
          <el-input 
            type="textarea" 
            v-model="postForm.ownerInfo" 
            placeholder="请输入主人联系方式等信息" 
            :rows="3"
            maxlength="500"></el-input>
        </el-form-item>
        
        <el-form-item label="状态">
          <el-radio-group v-model="postForm.status">
            <el-radio label="寻找中">寻找中</el-radio>
            <el-radio label="已结束">已结束</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="描述">
          <el-input 
            type="textarea" 
            v-model="postForm.description" 
            placeholder="请输入详细描述" 
            :rows="5"
            maxlength="2000"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitPost">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getUserAdoptionDetail, updateAdoptionPost, updateAdoptionPostStatus } from '@/api/adoption';

export default {
  name: 'UserAdoptionDetail',
  data() {
    return {
      post: null,
      loading: false,
      imageList: [],
      mainImage: '',
      
      // 放大镜相关
      showMagnifier: false,
      magnifierX: 0,
      magnifierY: 0,
      imageX: 0,
      imageY: 0,
      
      // 编辑弹窗相关
      dialogVisible: false,
      postForm: {
        id: null,
        title: '',
        description: '',
        petType: '狗',
        petGender: '公',
        petName: '',
        breed: '',
        vaccineStatus: '',
        photos: '',
        adoptionRequirement: '',
        location: '',
        ownerInfo: '',
        status: '寻找中'
      },
      
      // 图片上传相关
      uploadUrl: 'http://47.97.154.151:18001/api/file/upload',
      fileList: [],
      uploadedImages: []
    };
  },
  computed: {
    magnifierStyle() {
      return {
        left: this.magnifierX + 'px',
        top: this.magnifierY + 'px'
      };
    },
    magnifiedStyle() {
      return {
        backgroundImage: `url(${this.mainImage})`,
        backgroundPosition: `${this.imageX}% ${this.imageY}%`,
        backgroundSize: '250%'
      };
    },
    isMyPost() {
      if (!this.post) return false;
      const userInfo = JSON.parse(localStorage.getItem('userInfo'));
      return userInfo && userInfo.id === this.post.userId;
    }
  },
  created() {
    this.loadPostDetail();
  },
  methods: {
    // 加载帖子详情
    async loadPostDetail() {
      this.loading = true;
      try {
        const id = this.$route.params.id;
        const response = await getUserAdoptionDetail(id);
        
        if (response.data.success) {
          this.post = response.data.data;
          this.initImages();
        } else {
          this.$notify({
            title: '失败',
            message: response.data.message || '加载帖子详情失败',
            type: 'error',
            duration: 2000
          });
          this.goBack();
        }
      } catch (error) {
        this.$notify({
          title: '错误',
          message: '加载帖子详情失败，请稍后重试',
          type: 'error',
          duration: 2000
        });
        this.goBack();
      } finally {
        this.loading = false;
      }
    },
    
    // 初始化图片列表
    initImages() {
      if (this.post.photos) {
        this.imageList = this.post.photos.split(',').filter(img => img.trim());
      }
      
      if (this.imageList.length === 0) {
        this.imageList = ['https://img1.baidu.com/it/u=2531584226,2194794184&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500'];
      }
      
      this.mainImage = this.imageList[0];
    },
    
    // 选择图片
    selectImage(image) {
      this.mainImage = image;
    },
    
    // 鼠标移动事件（放大镜）
    handleMouseMove(event) {
      const container = event.currentTarget;
      const rect = container.getBoundingClientRect();
      
      const x = event.clientX - rect.left;
      const y = event.clientY - rect.top;
      
      const magnifierSize = 150;
      
      this.magnifierX = Math.max(0, Math.min(x - magnifierSize / 2, rect.width - magnifierSize));
      this.magnifierY = Math.max(0, Math.min(y - magnifierSize / 2, rect.height - magnifierSize));
      
      const percentX = (x / rect.width) * 100;
      const percentY = (y / rect.height) * 100;
      
      this.imageX = percentX;
      this.imageY = percentY;
      
      this.showMagnifier = true;
    },
    
    // 鼠标离开事件
    handleMouseLeave() {
      this.showMagnifier = false;
    },
    
    // 返回
    goBack() {
      this.$router.push('/user/adoption-list');
    },
    
    // 编辑帖子
    editPost() {
      this.postForm = {
        id: this.post.id,
        title: this.post.title,
        description: this.post.description || '',
        petType: this.post.petType,
        petGender: this.post.petGender,
        petName: this.post.petName,
        breed: this.post.breed,
        vaccineStatus: this.post.vaccineStatus || '',
        photos: this.post.photos || '',
        adoptionRequirement: this.post.adoptionRequirement || '',
        location: this.post.location || '',
        ownerInfo: this.post.ownerInfo || '',
        status: this.post.status
      };
      
      // 初始化文件列表
      this.fileList = [];
      this.uploadedImages = [];
      if (this.post.photos) {
        const images = this.post.photos.split(',');
        images.forEach((url, index) => {
          this.fileList.push({
            name: `image-${index}`,
            url: url
          });
          this.uploadedImages.push(url);
        });
      }
      
      this.dialogVisible = true;
    },
    
    // 结束帖子
    async endPost() {
      try {
        const userInfo = JSON.parse(localStorage.getItem('userInfo'));
        const response = await updateAdoptionPostStatus(this.post.id, {
          status: '已结束',
          currentUserId: userInfo.id
        });
        
        if (response.data.success) {
          this.$notify({
            title: '成功',
            message: '已标记为已结束',
            type: 'success',
            duration: 2000
          });
          this.loadPostDetail();
        } else {
          this.$notify({
            title: '失败',
            message: response.data.message || '操作失败',
            type: 'error',
            duration: 2000
          });
        }
      } catch (error) {
        this.$notify({
          title: '错误',
          message: '操作失败，请稍后重试',
          type: 'error',
          duration: 2000
        });
      }
    },
    
    // 重新开始寻找
    async reopenPost() {
      try {
        const userInfo = JSON.parse(localStorage.getItem('userInfo'));
        const response = await updateAdoptionPostStatus(this.post.id, {
          status: '寻找中',
          currentUserId: userInfo.id
        });
        
        if (response.data.success) {
          this.$notify({
            title: '成功',
            message: '已重新开始寻找',
            type: 'success',
            duration: 2000
          });
          this.loadPostDetail();
        } else {
          this.$notify({
            title: '失败',
            message: response.data.message || '操作失败',
            type: 'error',
            duration: 2000
          });
        }
      } catch (error) {
        this.$notify({
          title: '错误',
          message: '操作失败，请稍后重试',
          type: 'error',
          duration: 2000
        });
      }
    },
    
    // 图片上传成功
    handleUploadSuccess(response, file, fileList) {
      if (response.success) {
        this.uploadedImages.push(response.data);
        this.$notify({
          title: '成功',
          message: '图片上传成功',
          type: 'success',
          duration: 2000
        });
      } else {
        this.$notify({
          title: '失败',
          message: response.message || '图片上传失败',
          type: 'error',
          duration: 2000
        });
      }
    },
    
    // 移除图片
    handleRemove(file, fileList) {
      const index = this.uploadedImages.indexOf(file.url || file.response.data);
      if (index > -1) {
        this.uploadedImages.splice(index, 1);
      }
    },
    
    // 超出限制
    handleExceed() {
      this.$notify({
        title: '提示',
        message: '最多只能上传5张图片',
        type: 'warning',
        duration: 2000
      });
    },
    
    // 提交帖子
    async submitPost() {
      if (!this.postForm.title) {
        this.$notify({
          title: '提示',
          message: '请输入标题',
          type: 'warning',
          duration: 2000
        });
        return;
      }
      
      if (!this.postForm.petName) {
        this.$notify({
          title: '提示',
          message: '请输入宠物名称',
          type: 'warning',
          duration: 2000
        });
        return;
      }
      
      if (!this.postForm.breed) {
        this.$notify({
          title: '提示',
          message: '请输入品种',
          type: 'warning',
          duration: 2000
        });
        return;
      }
      
      try {
        const userInfo = JSON.parse(localStorage.getItem('userInfo'));
        
        const postData = {
          ...this.postForm,
          photos: this.uploadedImages.join(','),
          currentUserId: userInfo.id
        };
        
        const response = await updateAdoptionPost(postData);
        
        if (response.data.success) {
          this.$notify({
            title: '成功',
            message: '更新成功',
            type: 'success',
            duration: 2000
          });
          this.dialogVisible = false;
          this.loadPostDetail();
        } else {
          this.$notify({
            title: '失败',
            message: response.data.message || '更新失败',
            type: 'error',
            duration: 2000
          });
        }
      } catch (error) {
        this.$notify({
          title: '错误',
          message: '更新失败，请稍后重试',
          type: 'error',
          duration: 2000
        });
      }
    }
  }
};
</script>

<style scoped>
.adoption-detail-container {
  min-height: calc(100vh - 130px);
  margin-bottom: 30px;
}

.back-button {
  margin-bottom: 20px;
}

/* 图片区域 */
.image-section {
  position: sticky;
  top: 90px;
  overflow: visible;
}

.main-image-container {
  position: relative;
  width: 100%;
  height: 500px;
  background: #f5f7fa;
  border-radius: 12px;
  overflow: visible;
  cursor: crosshair;
}

.main-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 12px;
}

/* 放大镜 */
.magnifier {
  position: absolute;
  width: 150px;
  height: 150px;
  border: 2px solid #2c5f2d;
  background: rgba(255, 255, 255, 0.3);
  pointer-events: none;
  z-index: 10;
}

.magnified-view {
  position: absolute;
  right: -320px;
  top: 0;
  width: 300px;
  height: 300px;
  border: 2px solid #2c5f2d;
  background-color: white;
  background-repeat: no-repeat;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  pointer-events: none;
  z-index: 20;
}

/* 缩略图列表 */
.thumbnail-list {
  display: flex;
  gap: 10px;
  margin-top: 15px;
  flex-wrap: wrap;
}

.thumbnail-item {
  width: 80px;
  height: 80px;
  border: 2px solid #dcdfe6;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s;
}

.thumbnail-item:hover {
  border-color: #2c5f2d;
  transform: scale(1.05);
}

.thumbnail-item.active {
  border-color: #2c5f2d;
  box-shadow: 0 0 8px rgba(44, 95, 45, 0.3);
}

.thumbnail-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 帖子信息区域 */
.info-section {
  padding: 20px 0;
}

.post-title {
  font-size: 28px;
  font-weight: 700;
  color: #303133;
  margin-bottom: 15px;
  line-height: 1.4;
}

.post-meta {
  display: flex;
  gap: 10px;
  margin-bottom: 25px;
  flex-wrap: wrap;
}

/* 信息项 */
.info-item {
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e4e7ed;
}

.info-item:last-of-type {
  border-bottom: none;
}

.info-label {
  font-size: 15px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 10px;
}

.info-content {
  font-size: 14px;
  color: #606266;
  line-height: 1.8;
}

.info-content.description {
  white-space: pre-wrap;
}

.info-content i {
  margin-right: 5px;
  color: #2c5f2d;
}

/* 发布者信息 */
.publisher-section {
  background: linear-gradient(135deg, #f0f9f0 0%, #e6f4e6 100%);
  padding: 20px;
  border-radius: 12px;
  margin-bottom: 25px;
}

.publisher-header {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 15px;
}

.publisher-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.publisher-avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  object-fit: cover;
  border: 3px solid white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.publisher-details {
  flex: 1;
}

.publisher-nickname {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 8px;
}

.publisher-phone {
  font-size: 14px;
  color: #606266;
  display: flex;
  align-items: center;
  gap: 5px;
}

.publisher-phone i {
  font-size: 16px;
  color: #2c5f2d;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
}

/* 加载状态 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100px 0;
  gap: 15px;
}

.loading-container i {
  font-size: 40px;
  color: #2c5f2d;
}

.loading-container span {
  font-size: 16px;
  color: #909399;
}

/* 响应式设计 */
@media (max-width: 992px) {
  .image-section {
    position: relative;
    top: 0;
    margin-bottom: 30px;
  }

  .magnified-view {
    display: none;
  }

  .main-image-container {
    cursor: pointer;
  }

  .action-buttons {
    flex-direction: column;
  }

  .action-buttons .el-button {
    width: 100%;
  }
}

@media (max-width: 768px) {
  .post-title {
    font-size: 22px;
  }

  .main-image-container {
    height: 350px;
  }
}
</style>

